/*
  2017-04-07
*/
import React from 'react';
import Relay from "react-relay";
import { message } from 'antd';
import { router, hashHistory } from 'react-router';
import { Layout, Breadcrumb, Icon, Table, Button } from 'antd';
import Util from "../../util/Util";
import './css/MessageList.css';
import getAllCompanyListMutation from './mutation/getAllCompanyListMutation';
import getMessagesListMutation from './mutation/getMessagesListMutation';
import deleteMessagesMutation from './mutation/deleteMessagesMutation';
import updateMessagesMutation from './mutation/updateMessagesMutation';
import GetNewVersionOrderMutation from './mutation/GetNewVersionOrderMutation';
const {  Content, Sider } = Layout;

export default class MessageList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        totalResult : '',          //分页总条数
        pageSize : '10',      //每页显示条数
        pageNum : '1',        //当前页数
        companyList: '',
        messagesList: '',
        tableKey: '',
        otherEnId: '0',//其他企业ID
        msgStatus: null,
        selectedRowKeys: [],
        delete_high_light: false,
        selectedCompanyIndex: '0',
        enterpriseId: sessionStorage.getItem('enterpriseId')
    }
  }

  componentWillMount() {
    // this.getAllCompanyList()
    this.getMessagesList()
  }

  // getAllCompanyList() {
  //   //获取所有公司列表
  //   Relay.Store.commitUpdate(
  //       new getAllCompanyListMutation({
  //         enId: this.state.enterpriseId,
  //       }),
  //       {
  //           onFailure: () => {
  //               // console.log("请求失败")
  //           },
  //           onSuccess: (response) => {
  //             let errorCode = response.queryCompanysByEnId.queryCompanysByEnId.errorCode
  //             if (errorCode == 0) {
  //               let companyList = response.queryCompanysByEnId.queryCompanysByEnId.messageAll
  //               if (companyList && companyList.length) {
  //                 this.setState({
  //                   companyList: companyList,
  //                   otherEnId: companyList[0].companyYiId
  //                 })
  //                 this.getMessagesList()
  //               } else {
  //                 // console.log('公司列表为空');
  //                 this.setState({
  //                   messagesList: '',
  //                   totalResult: '0'
  //                 })
  //               }
  //             } else {
  //               // alert('请求失败')
  //             }
  //           }
  //       }
  //   );
  // }

  getMessagesList() {
    //获取所有消息列表
    Relay.Store.commitUpdate(
        new getMessagesListMutation({
          //  enId: this.state.enterpriseId,
     			 otherEnId: this.state.enterpriseId,
     			 pageNum: this.state.pageNum,
     			 pageSize: this.state.pageSize,
           msgStatus: this.state.msgStatus,
        }),
        {
            onFailure: () => {
                message.info('请求失败')
            },
            onSuccess: (response) => {
              let errorCode = response.queryMessageByCompanyIdAndEnId.queryMessageByCompanyIdAndEnId.errorCode;
              if (errorCode == 0) {
                let totalResult = response.queryMessageByCompanyIdAndEnId.queryMessageByCompanyIdAndEnId.totalResult;
                let messagesList = response.queryMessageByCompanyIdAndEnId.queryMessageByCompanyIdAndEnId.messageAll;
                if (messagesList && messagesList.length) {
                  messagesList.map((v, i)=> {
                    // if ( (v.msgType == '0' ||  v.msgType == '1') || (v.msgType == '2' && (v.actionStatus == '0' || v.actionStatus == '1' || v.actionStatus == '2') )) {
                      v.time = Util.dateFormat_hms(v.msgCreateDate)   //时间戳转换
                      v.details = v.msgDetails || v.yiDetail || v.jiaDetail  //消息内容判断
                      return v
                    // }
                  })
                  this.setState({
                    messagesList: messagesList,
                    totalResult: totalResult,
                    selectedRowKeys: [],
                  })
                } else {
                  this.setState({
                    messagesList: '',
                    totalResult: '0',
                    selectedRowKeys: [],
                  })
                }
              } else {
                message.info('消息列表请求失败')
              }
            }
        }
    );
  }
  /*删除消息*/
  deleteMessages() {
    Relay.Store.commitUpdate(
        new deleteMessagesMutation({
           arr: this.state.selectedRowKeys.join(',')
        }),
        {
            onFailure: () => {
                // console.log("删除请求失败")
            },
            onSuccess: (response) => {
              let errorCode = response.deleteMessages.deleteMessages.errorCode
              if (errorCode == 0) {
                // console.log('成功');
                this.getMessagesList()
              } else {
                // alert('请求失败')
              }
            }
        }
    );
  }
  /*修改已读未读状态*/
  updateMessages = (uuMid) => {
    Relay.Store.commitUpdate(
        new updateMessagesMutation({
           uuMid: uuMid
        }),
        {
            onFailure: () => {
                // console.log("删除请求失败")
            },
            onSuccess: (response) => {
              let errorCode = response.updateMsgById.updateMsgById.errorCode
              if (errorCode == 0) {
                this.getMessagesList()
              } else {
                // alert('请求失败')
              }
            }
        }
    );
  }
  /*页数改变*/
  pageChange(e) {
    let numtest = /^[0-9]*$/;
    let text = e.target.value;
    if (!numtest.test(text)) {
        return
    } else {
      this.setState({ pageNum: text})
    }
  }

  /*总页数*/
  pageTotal() {
      return Math.ceil(this.state.totalResult / this.state.pageSize)
  }
  /*上一页*/
  leftBtn() {
      if (this.state.pageNum <= 1) {
          return;
      } else {
          this.state.pageNum --;
          // this.bluron();
          this.setState({
              pageNum: this.state.pageNum,
          })
          this.getMessagesList()
      }
  }
  /*下一页*/
  rightBtn() {
      let pageTotal = this.pageTotal();
      if (this.state.pageNum >= pageTotal) {
          return;
      } else {
          this.state.pageNum++;
          this.setState({
              pageNum: this.state.pageNum,
          })
          this.getMessagesList()
          // alert(this.state.pageNum)
      }
  }
  /*确定按钮*/
  confirm() {
      let pageTotal = this.pageTotal();
      let pageNum = this.state.pageNum;
      if (pageNum < 1) {
          this.state.pageNum=1;
      } else if (pageNum > pageTotal) {
          this.state.pageNum = pageTotal;
      } else {
          this.state.pageNum = pageNum;
      }
      this.getMessagesList()
  }
  //消息列表点击
  messageTypeClick(type) {
    this.setState({
      msgStatus: type,
      pageNum : '1',
    }, () => {
      this.getMessagesList()
    })
  }
  //公司列表点击
  companyListClick(val, Index) {
    this.setState({
      otherEnId: val,
      pageNum: '1',
      selectedCompanyIndex: Index
    }, () => {
      this.getMessagesList()
    })
  }
  onSelectChange = (selectedRowKeys) => {
   this.setState({ selectedRowKeys: selectedRowKeys });
   if (selectedRowKeys != '') {
     this.setState({ delete_high_light: true })
   } else {
     this.setState({ delete_high_light: false })
   }
  }

  deleteClick = () => {
    this.deleteMessages()
    this.setState({
      selectedRowKeys: [],
      delete_high_light: false
    });
  }
  //左侧所有公司按钮点击
  allCompanyClick = () => {
    this.setState({
      otherEnId: null,
    }, () => {
      this.getMessagesList()
    })

  }
  getOrderStatus(record) {
    Relay.Store.commitUpdate(
        new GetNewVersionOrderMutation({
           enId: this.state.enterpriseId,
           orderId: record.orderId,
           status: record.orderStatus
        }),
        {
            onFailure: () => {
                message.error("请求失败")
            },
            onSuccess: (response) => {
              let errorCode = response.getNewVersionOrder.getNewVersionOrder.errorCode;
              let value = response.getNewVersionOrder.getNewVersionOrder.value;
              if (errorCode == 0) {
                // console.log('成功');
                 let enquiryId = response.getNewVersionOrder.getNewVersionOrder.order.enquiryId;
                 let orderStatus = response.getNewVersionOrder.getNewVersionOrder.order.status;
                 let activeKey = response.getNewVersionOrder.getNewVersionOrder.order.activeKey;
                 record.enquiryId = enquiryId;
                 if (activeKey != null) {
                   if (record.orderStatus == 1 || record.orderStatus == 2 || record.orderStatus == 3) {
                       hashHistory.push({pathname:'/OrderIndex/',state:{defaultActiveKey: activeKey,'record':record}});
                   } else if (record.orderStatus == 11 || record.orderStatus == 12) {
                       hashHistory.push({pathname:'/OrderIndex/',state:{defaultActiveKey: activeKey,'record':record}});
                   } else if (record.orderStatus == 8 || record.orderStatus == 9 || record.orderStatus == 10) {
                       hashHistory.push({pathname:'/OrderIndex/',state:{defaultActiveKey: activeKey,'record':record}});
                   }
                 } 
              } else {
                message.error(value)
              }
            }
        }
    );
  }
  //消息内容点击跳转方法
  cellClick = (record) => {
    //msgType 0 订单  根据actionStatus(7,8,9)和orderId 跳转订单详情或进度
    //   actionStatus：
    //   7：          跳转消息详情
    //   8：补充说明 跳订单进度 （订单进度添加按钮-->弹窗）
    //   9：其他的订单消息 跳转订单进度

      //msgType 1 不跳转 系统消息  请求接口改变状态
    //msgType 2 根据actionStatus  0-6 判断跳转贷款，结算，充值等列表，传递status状态，属于未完成还是已完成 0 是未完成 1 是已完成
    // actionStatus:
    // 0：企业端 后台充值
    // 1：企业端 借款扣除贷款
    // 2: 企业端 后台结算中心结算处理完
    // 3：金融公司 贷款自动发放
    // 4：金融公司 后台结算中心结算处理完
    // 5： 后台 企业申请结算
    // 6： 后台 企业申请贷款
    this.updateMessages(record.uuMid); //修改消息已读未读状态
    record.oid = record.orderId
    if (record.msgType == '0') {
        this.getOrderStatus(record)
    }
    else if (record.msgType == '2') {
      // 2: 企业端 后台结算处理完（转到具体的订单结算查看页面--》结算详情）
      // 11：企业端 后台寄出发票 （跳转到退税管理列表）
      // 12：企业端 发票审核失败 （跳转到订单结算列表页）
      if (record.actionStatus == 0) {   //  0 是充值，跳转账户充值充值
        hashHistory.push("/rechargerecordcompany?msgStatus="+record.status)
      }
      else if (record.actionStatus == 1 || record.actionStatus == 3 || record.actionStatus == 4 || record.actionStatus == 6) {  //跳转贷款
        hashHistory.push("/loanrecord?msgStatus="+record.status)
      }
      else if (record.actionStatus == 2 ) {  //结算详情
        let orderId = JSON.parse(record.send).orderId;
        hashHistory.push({pathname:'/settlementView/',state:{'orderId':orderId,'settle': 1}})
      } else if (record.actionStatus == 11) {
        hashHistory.push('/TaxRefundManagement')  //退税列表
      } else if (record.actionStatus == 12) {
        hashHistory.push('/settlementrecord') //订单结算列表
      }
    } else if (record.msgType == 6) {
        hashHistory.push({pathname:'/OrderIndex/',state:{defaultActiveKey: 10,'record':record}}); //打样进度
    } else if (record.msgType == 8) {
        // hashHistory.push('/orderpurchyes') //采购已签
        hashHistory.push({pathname:'/OrderIndex/',state:{defaultActiveKey: 1,'record':record}}); //订单详情
    }
  }

  render() {
    const columns = [
      {
        title: '时间',
        dataIndex: 'time',
        key: 'time',
        className: 'message_columns message_columns_left',
        render: (text, record) => {
          return (
            <span>
            {
              record.msgStatus == 0 ? <a style={{color: '#333',cursor:'default'}}><span className="message_unRead"></span>{record.time}</a> : <a style={{color: '#999'}}><span className="message_read"></span>{record.time}</a>
            }
            </span>
          )
        },
      },{
        title: '消息内容',
        dataIndex: 'details',
        key: 'details',
        className: 'message_columns message_columns_2 message_columns_left',
        render: (text, record) => {
          return (
            <span>
            {
              record.msgStatus == 0 ? <a style={{color: '#333'}}>{record.details}</a> : <a style={{color: '#999'}}>{record.details}</a>
            }
            </span>
          )
        },
        onCellClick: (record, event) => {
          this.cellClick(record)
        }
      }
    ];
    const companyArr = [
      {
        text: '未读消息',
        companyId: '0'
      },
      {
        text: '已读消息',
        companyId: '1'
      }
    ]
    const { selectedRowKeys, delete_high_light } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;
    return (
      <div className="message_list_box">
        <Layout style={{ height:'inherit',background:'#fff'}}>
          <Sider width={182} style={{ background: '#fff',display: 'none',borderRight: '1px solid #ededed' }}>
            <p className="message_title"  onClick={this.messageTypeClick.bind(this, null)}><i className="message_title_icon"></i>所有消息</p>
            <ul className="message_ul">
              {
                /*
                companyArr ? companyArr.map((v, i) => {
                  if (this.state.msgStatus == i) {
                      return <li className="active" onClick={this.messageTypeClick.bind(this, v.companyId)}>{v.text}</li>
                  }
                  return <li onClick={this.messageTypeClick.bind(this, v.companyId)}>{v.text}</li>
                }) : null
                */
              }
            </ul>
            {
              // <p className="message_title" onClick={this.allCompanyClick}><i className="message_title_icon"></i>所有公司</p>
            }
            <ol className="message_ul">
              {
                this.state.companyList ? this.state.companyList.map((v,i)=> {
                  if (i == this.state.selectedCompanyIndex) {
                    return <li key={i} className="active" onClick={this.companyListClick.bind(this, v.companyYiId, i)}>{v.companyName}</li>
                  } else {
                    return <li key={i} onClick={this.companyListClick.bind(this, v.companyYiId, i)}>{v.companyName}</li>
                  }
                }) : null
              }
            </ol>
          </Sider>
          <Content className="message_content">
            <Table
              columns={columns}
              dataSource={this.state.messagesList}
              className="production_main_message"
              pagination={false}
              rowKey={record => record.uuMid}
              // style={{width:'96%',margin: '30px 0 0 20px'}}
              rowSelection={rowSelection}
            />
          <br/>
            {/*分页*/}
            <div>
              {
                delete_high_light ? <Button className="message_delete selected" onClick={this.deleteClick}>删除</Button> : <Button className="message_delete" onClick={this.deleteClick}  >删除</Button>
              }
              <div className="message_pagination">
                <span>总计{this.state.totalResult}条</span>
                <span>共{this.pageTotal()}页</span>
                <span>第 <input style={{width: 20,border: '1px solid #ccc', borderRadius: '3px', textAlign: 'center'}}  value = {this.state.pageNum} onChange = {this.pageChange.bind(this)}/> 页</span>
                <button className="message_confirmBtn" onClick={this.confirm.bind(this)}>确定</button>
                <span className="message_prev_next_btn">
                  <b className="message_prev" onClick={this.leftBtn.bind(this)}></b>
                  <b className="message_next" onClick={this.rightBtn.bind(this)}></b>
                </span>
               </div>
            </div>

          </Content>
        </Layout>
      </div>
    )
  }
}
